import * as fs from 'fs';
import { dirname, join, relative } from 'path';

const OUTPUT_PATH = join(__dirname, '../src/modules/app/entities.ts');
const ENTITIES_PATH = dirname(OUTPUT_PATH); // 获取 entities.ts 文件的父目录路径

const entities: string[] = [];

fs.readdirSync(ENTITIES_PATH).forEach((folder) => {
  const entityFullPath = join(
    ENTITIES_PATH,
    folder,
    `./entities/${folder}.entity.ts`,
  );
  console.log(entityFullPath,fs.existsSync(entityFullPath));
  if (fs.existsSync(entityFullPath)) {
    // 计算相对路径
    let relativePath = relative(dirname(OUTPUT_PATH), entityFullPath);
    // 为了统一格式，确保路径以 ./ 开头，并使用 POSIX 风格
    if (!relativePath.startsWith('.')) {
      relativePath = './' + relativePath;
    }
    relativePath = relativePath.replace(/\\/g, '/'); // windows 兼容
    relativePath = relativePath.replace('.ts', '');
    entities.push(relativePath);
  }
});

async function main() {
  const str: string = entities
    .map((entity: string): string => `export * from '${entity}';\n`)
    .join('');

  // const template = fs.readFileSync('./templates/entity.ejs', 'utf-8');
  // const dtoFormattedStr = await prettierEslint({
  //   text: str,
  //   filePath: 'entities.ts',
  // });

  // 确保父目录存在
  fs.mkdirSync(dirname(OUTPUT_PATH), { recursive: true });
  fs.writeFileSync(OUTPUT_PATH, str);
}

/**
 * * 统一 app 下的 entity 文件
 */
main();
